/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int rob(TreeNode *root)
    {
        unordered_map<TreeNode *, TreeNode *> parent;
        unordered_map<TreeNode *, int> inDegree;

        function<void(TreeNode *, TreeNode *)> dfs =
            [&](TreeNode *t, TreeNode *p)
        {
            if (t == nullptr)
            {
                return;
            }
            inDegree[t] = 0;
            if (p != nullptr)
            {
                ++inDegree[p];
            }
            parent[t] = p;
            dfs(t->left, t);
            dfs(t->right, t);
        };

        dfs(root, nullptr);

        queue<TreeNode *> q;
        unordered_map<TreeNode *, array<int, 2>> dp;
        for (auto &[tree, inDeg] : inDegree)
        {
            if (inDeg == 0)
            {
                q.push(tree);
            }
        }

        while (!q.empty())
        {
            TreeNode *t = q.front();
            q.pop();
            dp[t][0] = 0;
            dp[t][1] = t->val;
            if (t->left != nullptr)
            {
                dp[t][0] += max(dp[t->left][0], dp[t->left][1]);
                dp[t][1] += dp[t->left][0];
            }
            if (t->right != nullptr)
            {
                dp[t][0] += max(dp[t->right][0], dp[t->right][1]);
                dp[t][1] += dp[t->right][0];
            }

            TreeNode *p = parent[t];
            if (p != nullptr)
            {
                --inDegree[p];
                if (inDegree[p] == 0)
                {
                    q.push(p);
                }
            }
        }

        return max(dp[root][0], dp[root][1]);
    }
};